package com.easy.app.controller.system;

import com.easy.framework.common.model.R;
import com.easy.framework.common.utils.Func;
import com.easy.framework.common.validate.Add;
import com.easy.framework.common.validate.Update;
import com.easy.framework.web.base.BaseController;
import com.easy.module.log.annotation.Log;
import com.easy.module.log.enums.Operation;
import com.easy.module.system.entity.SysUserDept;
import com.easy.module.system.query.SysUserDeptQuery;
import com.easy.module.system.service.ISysUserDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 用户部门信息
 *
 * @author Easy
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user/dept")
public class SysUserDeptController extends BaseController {

    private final ISysUserDeptService userDeptService;

    /**
     * 获取用户部门列表
     */
    @GetMapping("/list")
    public R<List<SysUserDept>> list(SysUserDeptQuery query) {
        if (Func.isNotEmpty(query.getUserId())) {
            return R.success(userDeptService.queryList(query));
        }
        return R.success();
    }

    /**
     * 编号获取详细信息
     */
    @GetMapping("/{id}")
    public R<SysUserDept> get(@PathVariable("id") Long id) {
        return R.success(userDeptService.getById(id));
    }

    /**
     * 新增用户部门
     */
    @PreAuthorize("@perm.hasPermission('system:user$edit')")
    @Log(title = "用户部门管理", type = Operation.INSERT)
    @PostMapping
    public R add(@Validated({Add.class}) @RequestBody SysUserDept userDept) {
        return R.result(userDeptService.addUserDept(userDept));
    }

    /**
     * 修改用户部门
     */
    @PreAuthorize("@perm.hasPermission('system:user$edit')")
    @Log(title = "用户部门管理", type = Operation.UPDATE)
    @PutMapping
    public R edit(@Validated({Update.class}) @RequestBody SysUserDept userDept) {
        return R.result(userDeptService.updateUserDept(userDept));
    }

    /**
     * 删除用户部门
     */
    @PreAuthorize("@perm.hasPermission('system:user$remove')")
    @Log(title = "用户部门管理", type = Operation.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable("ids") Long[] ids) {
        return R.result(userDeptService.removeBatchByIds(List.of(ids)));
    }
}
